/**
 * Copyright(C) 2018 Fugle Technology Co., Ltd. All rights reserved.
 */
package com.ifugle.rap.application.controller;

import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import com.ifugle.rap.application.model.AppUser;
import com.ifugle.rap.application.model.Result;
import com.ifugle.rap.application.model.UserBase;
import com.ifugle.rap.application.model.UserMaterial;
import com.ifugle.rap.application.model.UserPet;
import com.ifugle.rap.application.model.UserPlane;
import com.ifugle.rap.application.model.UserResult;
import com.ifugle.rap.application.model.UserTool;
import com.ifugle.rap.application.service.UserBaseService;
import com.ifugle.rap.application.service.UserMaterialService;
import com.ifugle.rap.application.service.UserPetService;
import com.ifugle.rap.application.service.UserPlaneService;
import com.ifugle.rap.application.service.UserService;
import com.ifugle.rap.application.service.UserToolService;
import com.ifugle.rap.common.error.ErrorCode;
import com.ifugle.rap.common.lang.exception.RuntimeException;
import com.ifugle.rap.common.result.ResultCode;
import com.ifugle.rap.common.result.ResultCodeRuntimeException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author HuangLei(wenyuan)
 * @version $Id UserController.java v 0.1 2018/8/7 HuangLei(wenyuan) Exp $
 */
@RestController
@RequestMapping("/airwarback")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserBaseService userBaseService;

    @Autowired
    UserPlaneService userPlaneService;

    @Autowired
    UserMaterialService userMaterialService;

    @Autowired
    UserPetService userPetService;

    @Autowired
    UserToolService userToolService;
    /***
     * 测试controller
     * @param userId
     * @return
     */
    @RequestMapping(value = "get-user-info", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public AppUser getUserById(Long userId) {
        AppUser appUser = userService.selectByPrimaryKey(userId);
        return appUser;
    }

    /***
     * 获取玩家基本信息
     * @param callback
     * @param userId
     * @return
     */
    @RequestMapping(value = "getinfo", method = RequestMethod.GET)
    @ResponseBody
    public Object register(String callback, String userId) {

        if (userId == null) {
            throw new ResultCodeRuntimeException(ResultCode.INVALID_PARAM, "非法的参数");
        }

        UserResult result = new UserResult();
        result.setCode("0");

        AppUser appUser = userService.selectByOpenId(userId);
        if (appUser == null) {
            appUser = new AppUser();
            appUser.setOpenId(userId);
            appUser.setNewer(1);
            appUser.setHaslottochance(1);
            appUser.setFight_index(1);
            appUser.setCoin(1000L);
            appUser.setDiamond(1000L);
            appUser.setMax_score(2000L);
            appUser.setName_index(userId);
            appUser.setName_changeable(userId);
            appUser.setUserName(UUID.randomUUID().toString());
            appUser.setNickName(UUID.randomUUID().toString());
            appUser.setAppId(UUID.randomUUID().toString());
            appUser.setAppSecret(UUID.randomUUID().toString());
            appUser.setAppName("超核特战");
            appUser.setAppToken(UUID.randomUUID().toString());
            appUser.setMission_unlock("0");
            //插入用户表
            userService.insert(appUser);
            UserBase userBase = new UserBase();
            userBase.setUserId(appUser.getId());
            userBase.setCoin(appUser.getCoin());
            userBase.setDiamond(appUser.getDiamond());
            userBase.setMaxScore(appUser.getMax_score());
            userBase.setMissionUnlock(false);//是否开启解锁，等级达到12级可以
            userBase.setBlackUnlock(false);
            userBase.setBlackLevel(0);
            userBase.setHasLottoChance(false);
            //插入用户基本表
            userBaseService.insert(userBase);
            appUser.setPlane_level("1,1,1,1");
            appUser.setPet_level("1,1,1,1");
            //初始化data，战机和宠物
            saveUserPet(appUser);
            saveUserPlane(appUser);
            result.setUser(appUser);
        }else{
            UserBase userbase = userBaseService.selectByUserId(appUser.getId());
            if (userbase != null) {

                //获取出战的飞机编号
                List<UserPlane> list= userPlaneService.selectByUserId(userbase.getUserId());
                StringBuffer levels = new StringBuffer();
                StringBuffer drives = new StringBuffer();
                if(CollectionUtils.isNotEmpty(list)){
                    for (int i = 0; i < list.size(); i++) {
                        long lev = list.get(i).getLevel();
                        String drv = list.get(i).getDriverName();
                        if (i == list.size() - 1) {
                            levels.append(lev);
                            drives.append(drv);
                        } else {
                            levels.append(lev + ",");
                            drives.append(drv + ",");
                        }
                    }
                }
                //获取宠物列表
                List<UserPet> petList = userPetService.selectByUserId(appUser.getId());
                StringBuffer petLevels = new StringBuffer();
                if (CollectionUtils.isNotEmpty(petList)) {
                    for (int i = 0; i < petList.size(); i++) {
                        long lev = petList.get(i).getLevel();
                        if (i == petList.size() - 1) {
                            petLevels.append(lev);
                        } else {
                            petLevels.append(lev + ",");
                        }
                    }
                }

                //获取tool列表
                List<UserTool> toolList = userToolService.selectByUserId(appUser.getId());
                StringBuffer toolArrstr = new StringBuffer();
                if (CollectionUtils.isNotEmpty(toolList)) {
                    for (int i = 0; i < toolList.size(); i++) {
                        long levs = toolList.get(i).getLevel();
                        if (i == toolList.size() - 1) {
                            toolArrstr.append(levs);
                        } else {
                            toolArrstr.append(levs + ",");
                        }
                    }

                }
                //获取材料列表
                List<UserMaterial> materialsList = userMaterialService.selectByUserId(appUser.getId());
                StringBuffer materialArrstr = new StringBuffer();
                if (CollectionUtils.isNotEmpty(materialsList)) {
                    for (int i = 0; i < materialsList.size(); i++) {
                        long levs = materialsList.get(i).getLevel();
                        if (i == toolList.size() - 1) {
                            materialArrstr.append(levs);
                        } else {
                            materialArrstr.append(levs + ",");
                        }
                    }
                }


                appUser.setNewer(0);
                appUser.setHaslottochance(userbase.getHasLottoChance() == true ? 1 : 0);

                //获取出战的飞机
                UserPlane plane = userPlaneService.selectEnableByUserId(appUser.getId());
                if (plane != null) {
                    appUser.setFight_index(plane.getPlaneId());
                }

                appUser.setCoin(userbase.getCoin());
                appUser.setDiamond(userbase.getDiamond());
                appUser.setMax_score(userbase.getMaxScore());
                appUser.setName_index(drives.toString());
                appUser.setName_changeable(drives.toString());

                //获取plane等级

                appUser.setPlane_level(levels.toString());
                appUser.setPet_level(petLevels.toString());
                appUser.setMaterial_array(materialArrstr.toString());
                appUser.setTool_array(toolArrstr.toString());

                appUser.setMission_unlock(userbase.getMissionUnlock() == true ? "1" : "0");
                appUser.setBlack_level(userbase.getBlackLevel());
            }
            result.setUser(appUser);
        }

        if (StringUtils.isBlank(callback)) {
            return appUser;
        }
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
        mappingJacksonValue.setJsonpFunction(callback);
        return mappingJacksonValue;
    }

    /***
     * 更新玩家基本信息
     * @param callback
     * @param userId
     * @param coin
     * @param diamond
     * @param maxScore
     * @return
     */
    @RequestMapping(value = "updatebase", method = RequestMethod.GET)
    @ResponseBody
    public Object updatebase(String callback, String userId, Long coin, Long diamond, Long maxScore) {
        if (userId == null) {
            throw new ResultCodeRuntimeException(ResultCode.INVALID_PARAM, "非法的参数");
        }
        AppUser appUser = userService.selectByOpenId(userId);
        if (appUser != null) {
            UserBase userBase = userBaseService.selectByUserId(appUser.getId());
            if(userBase!=null){
                userBase.setCoin(userBase.getCoin()+coin);
                userBase.setDiamond(userBase.getDiamond()+diamond);
                userBase.setMaxScore(userBase.getMaxScore()+maxScore);
                userBaseService.updateByPrimaryKey(userBase);
            }
        }
        String result = "success";
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
        mappingJacksonValue.setJsonpFunction(callback);
        return mappingJacksonValue;
    }

    /***
     *
     * 更新玩家信息
     * @param callback
     * @param fightIndex
     * @return
     */
    @RequestMapping(value = "updatefightplayer", method = RequestMethod.GET)
    @ResponseBody
    public Object updatefightplayer(String callback, String userId, String fightIndex) {
        if (userId == null) {
            throw new ResultCodeRuntimeException(ResultCode.INVALID_PARAM, "非法的参数");
        }
        AppUser user = userService.selectByOpenId(userId);
        if(user!=null){
            UserPlane userPlane = userPlaneService.selectByUserIdAndPlaneId(user.getId(), Long.parseLong(fightIndex));
            if (userPlane != null) {
                userPlane.setPlaneId(Integer.parseInt(fightIndex));
                userPlane.setIsEnable(true);
                //先把所有设为不可用
                userPlaneService.updateByUserId(user.getId());
                userPlaneService.updateByPrimaryKey(userPlane);
            }
        }
        String result = "success";
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
        mappingJacksonValue.setJsonpFunction(callback);
        return mappingJacksonValue;
    }

    /***
     *TODO  需要修复
     * 更新玩家信息
     * @param callback
     * @return
     */
    @RequestMapping(value = "updateplayer", method = RequestMethod.GET)
    @ResponseBody
    public Object updateplayer(String callback, String userId, String nameIndex, String nameChangeable) {
        if (userId == null) {
            throw new ResultCodeRuntimeException(ResultCode.INVALID_PARAM, "非法的参数");
        }
        AppUser appuser = userService.selectByOpenId(userId);
        if (appuser != null) {
            //修改玩家的账户名和昵称
            appuser.setUserName(nameIndex);
            appuser.setNickName(nameChangeable);
            userService.updateByPrimaryKey(appuser);
        }
        String result = "success";
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
        mappingJacksonValue.setJsonpFunction(callback);
        return mappingJacksonValue;
    }

    /***
     *
     * 更新战机
     * @param callback
     * @return
     */
    @RequestMapping(value = "updateplane", method = RequestMethod.GET)
    @ResponseBody
    public Object updateplane(String callback, String userId, Long coin, Long diamond, String planeLevel, String materialArray) {
        if (userId == null) {
            throw new ResultCodeRuntimeException(ResultCode.INVALID_PARAM, "非法的参数");
        }
        if(StringUtils.isNotBlank(materialArray)) {
            materialArray = materialArray.replace("undefined", "0").replace("NaN", "0");
        }
        AppUser appUser = userService.selectByOpenId(userId);
        if (appUser != null) {
            //modify base info
            handlerBaseInfo(coin, diamond, appUser);
            //修改战机属性，一般四个战机
            handlerPlane(planeLevel, appUser);

            //更新材料
            handlerMaterical(materialArray, appUser);
        }
        String result = "success";
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
        mappingJacksonValue.setJsonpFunction(callback);
        return mappingJacksonValue;
    }

    /***
     *
     * 更新宠物
     * @param callback
     * @return
     */
    @RequestMapping(value = "updatepet", method = RequestMethod.GET)
    @ResponseBody
    public Object updatepet(String callback, String userId, Long coin, Long diamond, String petLevel, String materialArray) {
        if (userId == null) {
            throw new ResultCodeRuntimeException(ResultCode.INVALID_PARAM, "非法的参数");
        }
        if(StringUtils.isNotBlank(materialArray)) {
            materialArray = materialArray.replace("undefined", "0").replace("NaN", "0");
        }

        AppUser appUser = userService.selectByOpenId(userId);
        if (appUser != null) {
            //modify base info
            handlerBaseInfo(coin, diamond, appUser);

            //修改宠物信息
            handlerpet(petLevel, appUser);

        }
        //处理材料
        handlerMaterical(materialArray, appUser);
        String result = "success";
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
        mappingJacksonValue.setJsonpFunction(callback);
        return mappingJacksonValue;
    }

    /***
     *
     * 更新宠物
     * @param callback
     * @return
     */
    @RequestMapping(value = "updatetool", method = RequestMethod.GET)
    @ResponseBody
    public Object updatetool(String callback, String userId, Long coin, Long diamond, String toolArrayStr, String hasLottoChance) {
        String result = "success";
        if(StringUtils.isNotBlank(toolArrayStr)) {
            toolArrayStr = toolArrayStr.replace("undefined", "0").replace("NaN", "0");
        }
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
        mappingJacksonValue.setJsonpFunction(callback);
        if (userId == null) {
            throw new ResultCodeRuntimeException(ResultCode.INVALID_PARAM, "非法的参数");
        }

        if (StringUtils.equals("0", hasLottoChance)) {
            return mappingJacksonValue;
        }
        AppUser appUser = userService.selectByOpenId(userId);
        if (appUser != null) {
            //modify base info
            handlerBaseInfo(coin, diamond, appUser);

            //修改tool信息
            handlerTool(toolArrayStr, appUser);
        }

        return mappingJacksonValue;
    }


    /***
     *
     * 更新宠物
     * @param callback
     * @return
     */
    @RequestMapping(value = "updatetotal", method = RequestMethod.GET)
    @ResponseBody
    public Object updatetotal(String callback, String userId, Long coin, Long diamond, Long maxScore, String toolArray, String materialArray,
            int missionUnlock, int blackLevel, int blackUnlock) {
        if (userId == null) {
            throw new ResultCodeRuntimeException(ResultCode.INVALID_PARAM, "非法的参数");
        }
        if(StringUtils.isNotBlank(materialArray)){
            materialArray = materialArray.replace("undefined", "0").replace("NaN", "0");
        }
        if(StringUtils.isNotBlank(toolArray)) {
            toolArray = toolArray.replace("undefined", "0").replace("NaN", "0");
        }

        AppUser appUser = userService.selectByOpenId(userId);
        if (appUser != null) {
            //modify base info
            UserBase userBase = userBaseService.selectByUserId(appUser.getId());
            if (userBase != null) {
                //修改基本信息表的金币，钻石
                userBase.setDiamond(userBase.getDiamond() + diamond);
                userBase.setCoin(userBase.getCoin() + coin);
                userBase.setBlackLevel(blackLevel);
                userBase.setMissionUnlock(missionUnlock == 1 ? true : false);
                userBase.setBlackUnlock(blackUnlock == 1 ? true : false);
                userBaseService.updateByPrimaryKey(userBase);
            }

            //修改tool信息
            handlerTool(toolArray, appUser);

            // modify mat
            handlerMaterical(materialArray, appUser);
        }
        String result = "success";
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
        mappingJacksonValue.setJsonpFunction(callback);
        return mappingJacksonValue;
    }

    /***
     * 处理基本信息
     * @param coin
     * @param diamond
     * @param appUser
     */
    private void handlerBaseInfo(Long coin, Long diamond, AppUser appUser) {
        UserBase userBase = userBaseService.selectByUserId(appUser.getId());
        if (userBase != null) {
            //修改基本信息表的金币，钻石
            userBase.setDiamond(userBase.getDiamond() + diamond);
            userBase.setCoin(userBase.getCoin() + coin);
            userBaseService.updateByPrimaryKey(userBase);
        }
    }

    /***
     * 处理战机
     * @param planeLevel
     * @param appUser
     */
    private void handlerPlane(String planeLevel, AppUser appUser) {
        List<UserPlane> userPlaneList = userPlaneService.selectByUserId(appUser.getId());
        if (CollectionUtils.isNotEmpty(userPlaneList)) {
            String[] planeLevels = planeLevel.split(",");
            for (int i = 0; i < planeLevels.length; i++) {
                UserPlane plane = new UserPlane();
                String levels = planeLevels[i];
                if (StringUtils.isBlank(levels) || StringUtils.equals("undefined", levels) || StringUtils.equals("NaN", levels)) {
                    levels = "0";
                }
                plane.setLevel(Integer.parseInt(levels));
                plane.setUserId(appUser.getId());
                plane.setPlaneId(i);
                userPlaneService.updateByUserIdAndPlaneId(plane);
            }
        } else {
            saveUserPlane(appUser);
        }
    }

    /***
     * 处理材料信息
     * @param materialArray
     * @param appUser
     */
    private void handlerMaterical(String materialArray, AppUser appUser) {
        if (StringUtils.isNotBlank(materialArray)) {
            String[] materialArrays = materialArray.split(",");
            for (int i = 0; i < materialArrays.length; i++) {
                String userMaterialId = materialArrays[i];
                if (StringUtils.isBlank(userMaterialId) || StringUtils.equals("undefined", userMaterialId) || StringUtils.equals("NaN", userMaterialId)) {
                    userMaterialId = "0";
                }
                UserMaterial userMaterial = userMaterialService.selectByUserIdAndmaterialId(appUser.getId(), Long.valueOf(userMaterialId));
                if (userMaterial != null) {
                    userMaterialService.updateByPrimaryKey(userMaterial);
                } else {
                    userMaterial = new UserMaterial();
                    userMaterial.setMaterialId(Long.valueOf(userMaterialId));
                    userMaterial.setUserId(appUser.getId());
                    userMaterial.setLevel(1);
                    userMaterial.setDescribes("材料属性");
                    userMaterialService.insert(userMaterial);
                }
            }
        }
    }

    /***
     * 处理工具类
     * @param toolArrayStr
     * @param appUser
     */
    private void handlerTool(String toolArrayStr, AppUser appUser) {
        if (StringUtils.isNotBlank(toolArrayStr)) {
            String[] toolArrayStrs = toolArrayStr.split(",");
            for (int i = 0; i < toolArrayStrs.length; i++) {
                String tools = toolArrayStrs[i];
                if (StringUtils.isBlank(tools) || StringUtils.equals("undefined", tools) || StringUtils.equals("NaN", tools)) {
                    tools = "0";
                }
                UserTool userTool = userToolService.selectByUserIdAndToolId(appUser.getId(), Long.valueOf(tools));
                if (userTool != null) {
                    userToolService.updateByPrimaryKey(userTool);
                } else {
                    userTool = new UserTool();
                    userTool.setToolId(Long.parseLong(tools));
                    userTool.setUserId(appUser.getId());
                    userTool.setLevel(1);
                    userTool.setDescribes("材料属性");
                    userToolService.insert(userTool);
                }
            }
        }
    }

    /***
     * 处理宠物信息
     * @param petLevel
     * @param appUser
     */
    private void handlerpet(String petLevel, AppUser appUser) {
        List<UserPet> userPetList = userPetService.selectByUserId(appUser.getId());
        if (CollectionUtils.isNotEmpty(userPetList)) {
            //更新宠物等级
            String[] pets = petLevel.split(",");
            for (int i = 0; i < pets.length; i++) {
                String leves = pets[i];
                if (StringUtils.isBlank(leves) || StringUtils.equals("undefined", leves) || StringUtils.equals("NaN", leves)) {
                    leves = "0";
                }

                UserPet pet = new UserPet();
                pet.setUserId(appUser.getId());
                pet.setPetId(Long.valueOf(i));
                pet.setLevel(Integer.parseInt(leves));
                userPetService.updateByUserIdAndPetId(pet);
            }

        } else {
            saveUserPet(appUser);
        }
    }

    private void saveUserPet(AppUser appUser) {
        for (int i = 0; i < 4; i++) {
            UserPet pet = new UserPet();
            pet.setUserId(appUser.getId());
            pet.setPetId(Long.valueOf(i));
            pet.setLevel(1);
            pet.setDescribes("宠物");
            userPetService.insert(pet);
        }
    }

    private void saveUserPlane(AppUser appUser) {
        for (int i = 0; i < 4; i++) {
            UserPlane plane = new UserPlane();
            plane.setUserId(appUser.getId());
            plane.setPlaneId(i);
            plane.setLevel(1);//初始化一级

            switch (i) {
            case 0:
                plane.setDriverName("0");
                plane.setPlaneName("时空战舰");
                break;
            case 1:
                plane.setDriverName("1");
                plane.setPlaneName("宇宙之魂");
                break;

            case 2:
                plane.setDriverName("2");
                plane.setPlaneName("银河航母");
                break;

            case 3:
                plane.setDriverName("3");
                plane.setPlaneName("铁血丹心");
                break;

            default:
                break;
            }

            plane.setDescribes(plane.getDriverName() + "-" + plane.getPlaneName());
            plane.setIsEnable(false);
            userPlaneService.insert(plane);
        }
    }

}
